package com.zero.zsingleton
{
	import flash.system.ApplicationDomain;
	
	import com.zero.zmodel.ComponentModel;
	import com.zero.zutils.ClassUtils;
	import com.zero.zutils.ObjectUtils;

	public class ComponentSingleton
	{
		private static var _instance:ComponentSingleton;
		
		private var _model:ComponentModel;
		
		public function ComponentSingleton()
		{
			_model = new ComponentModel();
			ClassUtils.uiSourceDomain = ApplicationDomain.currentDomain;
		}
		
		public static function get instance():ComponentSingleton
		{
			if(_instance == null)
			{
				_instance = new ComponentSingleton();
			}
			
			return _instance;
		}
		
		public function get model():ComponentModel
		{
			return _model;
		}
		
		public function createComponentByStylename($stylename:String, args:Array=null):*
		{
			var style:XML = getComponentStyle($stylename);
			var classname:String = style.@classname;
			var component:* = ClassUtils.CreatInstance(classname,args);
//			if(ClassUtils.classIsComponent(classname))
//			{
//				component.beginChanges();
//				ObjectUtils.copyPorpertiesByXML(component,style);
//				component.commitChanges();
//			}else
//			{
				ObjectUtils.copyPorpertiesByXML(component,style);
//			}
			return component;
		}
		
		private function getComponentStyle(stylename:String):XML
		{
			var style:XML = _model.getComonentStyle(stylename);
			while(style.hasOwnProperty("@parentStyle"))
			{
				var parentStyle:XML = _model.getComonentStyle(String(style.@parentStyle));
				delete style.@parentStyle;
				ObjectUtils.combineXML(style,parentStyle);
			}
			return style;
		}
	}
}